/*
 * @description: Ajax_ES6_Promise版
 * @author: HuiSir
 * @update: 20190222
 */	
function ajax({type='GET',url,data,timeout=999999}){  //timeout-超时时间
	let xhr = new XMLHttpRequest() , domain = 'http://172.18.3.76:8080/myopia'  //需要预先配置
	type = type.toUpperCase()	//转换为大写
	//返回Promise对象，调用时使用then链式回调
	return new Promise((resolve, reject) => {
		if(type!='JSONP'){	//post|get
			xhr.timeout = timeout	//超时设置
			switch(type){
				case 'POST':
					xhr.open(type,domain+url,true)
					if(data.constructor.name != 'FormData'){	//如果是上传文件用的FormData就不设置请求头
						xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')	//请求头
					}
					xhr.send(data.constructor.name == 'FormData'?data:params(data))
				break;
				default:
					xhr.open(type,domain+url+'?'+params(data),true)
					xhr.send()
			}
			xhr.onreadystatechange = ()=>{
				if(xhr.readyState==4){
					if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
						resolve(JSON.parse(xhr.responseText))	//成功
					}else{
						if(xhr.responseText.length>0){	//错误
							reject(JSON.parse(xhr.responseText))	
						}else{
							reject(xhr.status)
						}
					}
				}
			}
		}else{	//jsonp
			var isRes = 0
			let timer = setTimeout(()=>{
					isRes = 1
					reject({status:0,msg:'请求超时！'})	//错误
				},timeout)
			let arr = []
			data.cbkey = data.cbkey || 'callback'
			data.callback = data.callback || 'jsonp_cb_' + Date.now()
			for (let key in data) {
				if(key!='cbkey' && key!='callback'){
					arr.push(key + '=' + data[key])
				}
			}
			let parames = arr.join('&') , newScript = document.createElement('script')
			newScript.src = domain+url+'?'+ data.cbkey + '=' + data.callback + '&' + parames
			document.body.appendChild(newScript)
			window[data.callback] = res=>{
				clearTimeout(timer)
				if(isRes == 0){
					resolve(res)
					delete window[data.callback]  //删除对象
					document.body.removeChild(newScript)  //删除创建的内容
				}else{
					delete window[data.callback]  //删除对象
					document.body.removeChild(newScript)  //删除创建的内容
				}
			}
		}
	})
}

/* 请求数据转换为formData格式 */
function params(data){
	var arr = []
	for(var prop in data){
		arr.push(prop + "=" + data[prop])
	}
	return arr.join("&")
}

export default ajax

/* 请求异步处理，解决回调地狱 */
/* ajax({type:'post',url:'/url',data:{name:'张三',age:18}}).then(res1=>{
	console.log(res1)
	return ajax({url:'/url',data:{name:'张三',age:18},timeout:3000})
}).then(res2=>{
	console.log(res2)
}).catch(err=>{
	console.log(err)
}) */